package com.inno.subject.domain.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.inno.subject.common.enums.IsDeletedFlagEnum;
import com.inno.subject.common.error.BusinessException;
import com.inno.subject.domain.convert.SubjectCategoryConverter;
import com.inno.subject.domain.entity.SubjectCategoryBO;
import com.inno.subject.domain.service.SubjectCategoryDomainService;
import com.inno.subject.domain.utils.CacheUtil;
import com.inno.subject.infra.basic.entity.PlannerSubjectCategory;
import com.inno.subject.infra.basic.service.PlannerSubjectCategoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Slf4j
@Service
@RequiredArgsConstructor
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {
    private final PlannerSubjectCategoryService plannerSubjectCategoryService;
    private final CacheUtil<SubjectCategoryBO> cacheUtil;

    private static final String CACHE_CATEGORY_TREE = "category_tree";

    @Override
    public List<SubjectCategoryBO> queryList(SubjectCategoryBO subjectCategoryDTO) {
        // 如果是查询所有  那么subjectCategoryDTO中的id为0
        // 如果id不为空  就查询某个分类下的所有子分类
        Long categoryId = subjectCategoryDTO.getId();

        return cacheUtil.getCategoryTree(CACHE_CATEGORY_TREE, SubjectCategoryBO.class,
                (id) -> buildFullCategoryTree(),
                this::buildSubCategoryTree,
                categoryId);


    }

    @Override
    public void add(SubjectCategoryBO subjectCategoryBO) {
        PlannerSubjectCategory category4DB = this.plannerSubjectCategoryService.queryByCategoryName(subjectCategoryBO.getCategoryName());

        if (Objects.nonNull(category4DB)){
            throw new BusinessException("该分类已经存在");
        }
        category4DB  = new PlannerSubjectCategory();
        category4DB.setCategoryName(subjectCategoryBO.getCategoryName());
        category4DB.setId(IdUtil.getSnowflakeNextId());
        category4DB.setParentId(subjectCategoryBO.getParentId());
        category4DB.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode().toString());
        this.plannerSubjectCategoryService.insert(category4DB);
        cacheUtil.clearUp(CACHE_CATEGORY_TREE);
    }

    @Override
    public void delete(Long id) {
        PlannerSubjectCategory category = new PlannerSubjectCategory();
        category.setId(id);
        category.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode().toString());
        List<PlannerSubjectCategory> children = this.plannerSubjectCategoryService.queryByParentId(id);
        if (CollectionUtil.isNotEmpty(children)){
            for (PlannerSubjectCategory child : children) {
                delete(child.getId());
            }
        }
        this.plannerSubjectCategoryService.update(category);
        cacheUtil.clearUp(CACHE_CATEGORY_TREE);
    }

    private List<SubjectCategoryBO> buildFullCategoryTree() {
        // 先查询出所有未删除的分类记录
        List<PlannerSubjectCategory> allCategories = plannerSubjectCategoryService.queryAllNotDeletedCategories();

        List<SubjectCategoryBO> boList = SubjectCategoryConverter.INSTANCE.convertEntityListToBOList(allCategories);

        // 构建分类树的根节点列表
        List<SubjectCategoryBO> rootCategories = new ArrayList<>();
        for (SubjectCategoryBO category : boList) {
            if (category.getParentId() == 0) {
                rootCategories.add(category);
            }
        }

        // 为每个根节点构建子树
        for (SubjectCategoryBO rootCategory : rootCategories) {
            buildSubTree(rootCategory, boList);
        }

        return rootCategories;
    }

    private List<SubjectCategoryBO> buildSubCategoryTree(Long parentId) {
        // 先查询出所有未删除的分类记录
        List<PlannerSubjectCategory> allCategories = plannerSubjectCategoryService.queryAllNotDeletedCategories();
        List<SubjectCategoryBO> boList = SubjectCategoryConverter.INSTANCE.convertEntityListToBOList(allCategories);

        // 找到指定父分类
        SubjectCategoryBO parentCategory = null;
        for (SubjectCategoryBO category : boList) {
            if (category.getId().equals(parentId)) {
                parentCategory = category;
                break;
            }
        }

        if (parentCategory != null) {
            // 为指定父分类构建子树
            buildSubTree(parentCategory, boList);
            return List.of(parentCategory);
        } else {
            return List.of();
        }
    }

    private void buildSubTree(SubjectCategoryBO parentCategory, List<SubjectCategoryBO> allCategories) {
        List<SubjectCategoryBO> children = new ArrayList<>();
        for (SubjectCategoryBO category : allCategories) {
            if (category.getParentId().equals(parentCategory.getId())) {
                children.add(category);
            }
        }
        parentCategory.setChildren(children);

        // 递归构建每个子节点的子树
        for (SubjectCategoryBO child : children) {
            buildSubTree(child, allCategories);
        }
    }

}
